<?php

namespace app\common\model\banxi\learn;

use app\common\model\banxi\student\Student;
use app\common\model\banxi\trainer\Trainer;
use app\common\model\common\BaseModel;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 上课记录
 */
class LearnTwentyAntiForgetting extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_learn_twenty_anti_forgetting';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
    ];


    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'skRecordId' => 'string',
        'studentId' => 'string',
        'trainerAntiForgettingId' => 'string',
        'isReview' => 'boolean',
        'isTeach' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function updateTrainer($id, $trainerId)
    {
        return $this->update(['trainerAntiForgettingId' => $trainerId], ['id' => $id]);
    }

    public function updateTrainerSkAll($skRecordId, $trainerId)
    {
        Db::startTrans();
        try {
            $nowDate = date('Y-m-d H:i:s');
            $records = $this->where([
                ['skRecordId', '=', $skRecordId],
            ])->whereRaw("CONCAT(`date`, ' ', `time`)  > '$nowDate'")
                ->select();
            foreach ($records as $record) {
                $record->trainerAntiForgettingId = $trainerId;
                $record->save();
            }
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());
        }
        return true;

    }


    /**
     * 获取上课记录第一个抗遗忘分组ID
     */
    public function getGroupIdBySkRecord($recordId)
    {
        return $this->where('skRecordId', $recordId)
            ->value('groupId');
    }

    public function listDateBySkRecord($recordId, $groupId)
    {
        $dateList = $this->where('skRecordId', $recordId)
            ->whereLike('groupId', $groupId)
            ->column('date');
        $result  = [];
        foreach ($dateList as $date) {
            $result[] = date('m-d', strtotime($date));
        }

        return $result;
    }

    /**
     * 将记录按日期分组包装
     *
     * @param array $trainerList 记录列表
     * @return array
     */
    public function wrapperReviewDate($trainerList)
    {
        $result = [];

        // 按日期进行分组
        $dateGroupMap = [];
        foreach ($trainerList as $item) {
            $date = $item['date'];
            if (!isset($dateGroupMap[$date])) {
                $dateGroupMap[$date] = [];
            }
            $dateGroupMap[$date][] = $item;
        }

        // 构造 ReviewDate 对象
        foreach ($dateGroupMap as $date => $values) {
            $reviewDate = [
                'date' => $date,
                'recordList' => $values
            ];
            $result[] = $reviewDate;
        }

        // 按日期正序排序
        usort($result, function ($a, $b) {
            return strcmp($a['date'], $b['date']);
        });

        return $result ?? [];
    }

    /**
     * V2版本的日期分组包装方法
     *
     * @param array $trainerList 记录列表
     * @return array
     */
    private function wrapperReviewDateV2($trainerList)
    {
        $result = [];

        // 按日期进行分组
        $dateGroupMap = [];
        foreach ($trainerList as $item) {
            $date = $item['date'];
            if (!isset($dateGroupMap[$date])) {
                $dateGroupMap[$date] = [];
            }
            $dateGroupMap[$date][] = $item;
        }

        // 处理每个日期组
        foreach ($dateGroupMap as $date => $values) {
            $reviewDate = [
                'date' => $date,
                'recordList' => []
            ];

            // 按学生ID分组
            $studentValues = [];
            foreach ($values as $value) {
                $studentId = $value['studentId'];
                if (!isset($studentValues[$studentId])) {
                    $studentValues[$studentId] = [];
                }
                $studentValues[$studentId][] = $value;
            }

            // 处理每个学生组
            $recordList = [];
            foreach ($studentValues as $studentId => $studentValuesList) {
                // 按ID排序
                usort($studentValuesList, function ($a, $b) {
                    return $a['id'] <=> $b['id'];
                });

                // 取第一个记录作为基础
                $firstRecord = $studentValuesList[0];
                $record = [
                    'id' => $firstRecord['id'],
                    'title' => $firstRecord['title'],
                    'date' => $firstRecord['date'],
                    'time' => $firstRecord['time'],
                    'isReview' => $firstRecord['isReview'],
                    'isTeach' => $firstRecord['isTeach']
                ];

                // 收集所有记录的IDs
                $ids = [];
                $groupIds = [];
                foreach ($studentValuesList as $item) {
                    $ids[] = $item['id'];
                    $groupIds[] = $item['groupId'];
                }
                $record['ids'] = $ids;
                $record['groupIds'] = $groupIds;

                // 添加学员信息
                $record['studentInfo'] = [
                    'id' => $firstRecord['studentInfo']['ID'],
                    'name' => $firstRecord['studentInfo']['name']
                ];

                $recordList[] = $record;
            }

            $reviewDate['recordList'] = $recordList;
            $result[] = $reviewDate;
        }

        // 按日期正序排序
        usort($result, function ($a, $b) {
            return strcmp($a['date'], $b['date']);
        });

        return $result;
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function studentInfo()
    {
        return $this->hasOne(Student::class, 'id', 'studentId');
    }

    public function trainerInfo()
    {
        return $this->hasOne(Trainer::class, 'id', 'trainerAntiForgettingId');
    }

}